<template>
  <div class="check-admin-history-container">
    <el-card class="filter-card">
      <el-form :inline="true" :model="filterForm" class="filter-form">
        <el-form-item :label="$t('group.name')">
          <el-select v-model="filterForm.groupId" :placeholder="$t('common.pleaseSelect') + ' ' + $t('group.name')" clearable>
            <el-option
              v-for="group in groups"
              :key="group.id"
              :label="group.name"
              :value="group.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('attendance.courseName')">
          <el-select v-model="filterForm.courseId" :placeholder="$t('common.pleaseSelect') + ' ' + $t('attendance.courseName')" clearable>
            <el-option
              v-for="course in courses"
              :key="course.id"
              :label="course.name"
              :value="course.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('common.status')">
          <el-select v-model="filterForm.state" :placeholder="$t('attendance.approveStatus')" clearable>
            <el-option :label="$t('common.all')" :value="null"></el-option>
            <el-option :label="$t('attendance.approved')" :value="1"></el-option>
            <el-option :label="$t('attendance.rejected')" :value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('common.dateRange')">
          <el-date-picker
            v-model="filterForm.dateRange"
            type="daterange"
            :range-separator="$t('common.to')"
            :start-placeholder="$t('common.startDate')"
            :end-placeholder="$t('common.endDate')"
            value-format="yyyy-MM-dd"
            @change="handleDateRangeChange">
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleFilter">{{ $t('common.search') }}</el-button>
          <el-button @click="resetFilter">{{ $t('common.reset') }}</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 当前筛选状态显示区域 -->
    <div class="filter-status" v-if="hasActiveFilters">
      <span>{{ $t('attendance.currentFilter') }}: </span>
      <el-tag v-if="filterForm.groupId" size="small" closable @close="removeFilter('groupId')">
        {{ $t('group.name') }}: {{ getFilterGroupName() }}
      </el-tag>
      <el-tag v-if="filterForm.courseId" size="small" type="success" closable @close="removeFilter('courseId')">
        {{ $t('attendance.courseName') }}: {{ getFilterCourseName() }}
      </el-tag>
      <el-tag v-if="filterForm.state !== null" size="small" type="warning" closable @close="removeFilter('state')">
        {{ $t('common.status') }}: {{ getStateText() }}
      </el-tag>
      <el-tag v-if="filterForm.startDate && filterForm.endDate" size="small" type="info" closable @close="removeFilter('dateRange')">
        {{ $t('common.date') }}: {{ filterForm.startDate }} {{ $t('common.to') }} {{ filterForm.endDate }}
      </el-tag>
    </div>

    <el-table
      :data="leaveList"
      style="width: 100%"
      border
      v-loading="loading"
      :row-class-name="getRowClassName">
      <el-table-column
        :label="$t('attendance.studentName')"
        min-width="100">
        <template slot-scope="scope">
          {{ getUserName(scope.row) }}
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('group.name')"
        min-width="120">
        <template slot-scope="scope">
          {{ getGroupName(scope.row) }}
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('attendance.courseName')"
        min-width="120">
        <template slot-scope="scope">
          {{ getCourseName(scope.row) }}
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('attendance.leaveType')"
        min-width="100">
        <template slot-scope="scope">
          <el-tag size="medium" :type="getLeaveTypeTagType(scope.row.leaveTypeId)">{{ getLeaveTypeName(scope.row.leaveTypeId) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('attendance.leaveReason')"
        min-width="100">
        <template slot-scope="scope">
          {{ scope.row.reason }}
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('attendance.leaveDate')"
        min-width="160">
        <template slot-scope="scope">
          {{ formatDate(scope.row.leaveDate) }}
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('attendance.approveStatus')"
        min-width="100"
        sortable>
        <template slot-scope="scope">
          <el-tag :type="getStatusType(scope.row.state)">
            {{ getStatusText(scope.row.state) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('attendance.approveRemark')"
        min-width="200"
        v-if="!isMobile">
        <template slot-scope="scope">
          {{ scope.row.approveRemark }}
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination-container">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pageSize"
        :layout="paginationLayout"
        :total="total">
      </el-pagination>
    </div>
  </div>
</template>

<script>
import ElementUI from "element-ui";
import { mapGetters } from 'vuex';

export default {
  name: "LeaveAdminHistory",
  data() {
    return {
      filterForm: {
        groupId: '',
        courseId: '',
        state: '',
        dateRange: [],
        startDate: null,
        endDate: null
      },
      groups: [],
      courses: [],
      leaveList: [],
      loading: false,
      currentPage: 1,
      pageSize: 10,
      total: 0,
      isMobile: false,
      paginationLayout: "total, sizes, prev, pager, next, jumper",
      leaveTypes: [
        { id: 1, name: this.$t('attendance.checkAdmin.personalLeave') },
        { id: 2, name: this.$t('attendance.checkAdmin.sickLeave') },
        { id: 3, name: this.$t('attendance.checkAdmin.otherLeave') },
        { id: 4, name: this.$t('common.other') }
      ]
    }
  },
  created() {
    this.getGroups();
    this.getCourses();
    this.loadData();
    this.checkScreenSize();
  },
  mounted() {
    window.addEventListener('resize', this.checkScreenSize);
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.checkScreenSize);
  },
  computed: {
    ...mapGetters(['getUserId']),
    // 判断是否有活动筛选
    hasActiveFilters() {
      return this.filterForm.groupId || this.filterForm.courseId || this.filterForm.state !== null || 
             (this.filterForm.startDate && this.filterForm.endDate);
    }
  },
  methods: {
    // 检查屏幕尺寸并设置相应的布局
    checkScreenSize() {
      this.isMobile = document.body.clientWidth < 768;
      // 根据屏幕尺寸调整分页控件布局
      if (this.isMobile) {
        this.paginationLayout = "prev, pager, next";
      } else {
        this.paginationLayout = "total, sizes, prev, pager, next, jumper";
      }
    },
    
    // 获取班级列表
    getGroups() {
      this.$axios.get("/group/list").then(res => {
        if (res.code === 200) {
          this.groups = res.data || [];
        } else {
          ElementUI.Message.error(res.data.msg || this.$t('attendance.checkAdmin.getClassFailed'));
        }
      }).catch(error => {
        console.error('获取班级列表失败:', error);
        ElementUI.Message.error(this.$t('attendance.checkAdmin.getClassFailed'));
      });
    },
    
    // 获取课程列表
    getCourses() {
      this.$axios.get(`/course/teacher/${this.getUserId}`).then(res => {
        if (res.code === 200) {
          this.courses = res.data || [];
        } else {
          ElementUI.Message.error(res.data.msg || this.$t('attendance.checkAdmin.getCourseFailed'));
        }
      }).catch(error => {
        console.error('获取课程列表失败:', error);
        ElementUI.Message.error(this.$t('attendance.checkAdmin.getCourseFailed'));
      });
    },
    
    // 加载请假记录数据
    loadData() {
      this.loading = true;
      const params = {
        current: this.currentPage,
        size: this.pageSize,
        groupId: this.filterForm.groupId || null,
        courseId: this.filterForm.courseId || null,
        startDate: this.filterForm.startDate || null,
        endDate: this.filterForm.endDate || null
      };
      
      // 处理状态筛选
      if (this.filterForm.state !== '' && this.filterForm.state !== null) {
        params.state = this.filterForm.state;
      }
      
      this.$axios.get("/leave/page", { params }).then(res => {
        this.loading = false;
        if (res.code === 200) {
          //console.log('请假历史数据返回:', res.data);
          
          // 获取请假记录
          const records = res.data.records || [];
          this.total = res.data.total || 0;
          
          // 获取所有用户ID和课程ID
          const userIds = [...new Set(records.map(record => record.userId))];
          const courseIds = [...new Set(records.map(record => record.courseId))];
          
          // 创建Promise数组
          const promises = [];
          
          // 获取用户信息
          if (userIds.length > 0) {
            const userPromises = userIds.map(userId => 
              this.$axios.get(`/user/${userId}`).catch(err => {
                console.error(`获取用户信息失败 ID: ${userId}`, err);
                return { data: { code: 500 } };
              })
            );
            promises.push(Promise.all(userPromises).then(responses => {
              const userMap = {};
              responses.forEach((res, index) => {
                if (res.code === 200) {
                  userMap[userIds[index]] = res.data;
                }
              });
              return { type: 'users', data: userMap };
            }));
          }
          
          // 获取课程信息
          if (courseIds.length > 0) {
            const coursePromises = courseIds.map(courseId => 
              this.$axios.get(`/course/detail/${courseId}`).catch(err => {
                console.error(`获取课程信息失败 ID: ${courseId}`, err);
                return { data: { code: 500 } };
              })
            );
            promises.push(Promise.all(coursePromises).then(responses => {
              const courseMap = {};
              responses.forEach((res, index) => {
                if (res.code === 200) {
                  courseMap[courseIds[index]] = res.data;
                }
              });
              return { type: 'courses', data: courseMap };
            }));
          }
          
          // 等待所有请求完成
          Promise.all(promises).then(results => {
            let userMap = {};
            let courseMap = {};
            
            results.forEach(result => {
              if (result.type === 'users') {
                userMap = result.data;
              } else if (result.type === 'courses') {
                courseMap = result.data;
              }
            });
            
            // 将用户和课程信息添加到请假记录中
            this.leaveList = records.map(record => {
              const user = userMap[record.userId] || {};
              const course = courseMap[record.courseId] || {};
              const group = this.groups.find(g => g.id === user.groupId);
              
              return {
                ...record,
                userName: user.name || this.$t('common.unknown'),
                groupName: group ? group.name : this.$t('common.unknown'),
                courseName: course.name || this.$t('common.unknown')
              };
            });
            
            // 调试输出
            if (this.leaveList.length > 0) {
              //console.log('处理后的请假历史数据示例:', JSON.stringify(this.leaveList[0]));
            }
          });
        } else {
          ElementUI.Message.error(res.data.msg || this.$t('attendance.checkAdmin.noHistoryRecords'));
        }
      }).catch((error) => {
        console.error('请求失败:', error);
        this.loading = false;
        ElementUI.Message.error(this.$t('common.operationFailedRetry'));
      });
    },
    
    // 处理筛选
    handleFilter() {
      this.currentPage = 1;
      this.loadData();
    },
    
    // 重置筛选
    resetFilter() {
      this.filterForm = {
        groupId: '',
        courseId: '',
        state: '',
        dateRange: [],
        startDate: null,
        endDate: null
      };
      this.handleFilter();
    },
    
    // 格式化日期
    formatDate(dateStr) {
      if (!dateStr) return '';
      const date = new Date(dateStr);
      return date.toLocaleString();
    },
    
    // 获取状态文本
    getStatusText(state) {
      const statusMap = {
        0: this.$t('attendance.checkAdmin.pending'),
        1: this.$t('attendance.checkAdmin.approved'),
        2: this.$t('attendance.checkAdmin.rejected')
      };
      return statusMap[state] || this.$t('common.unknown');
    },
    
    // 获取状态标签类型
    getStatusType(state) {
      const typeMap = {
        0: 'info',
        1: 'success',
        2: 'danger'
      };
      return typeMap[state] || 'info';
    },
    
    handleSizeChange(val) {
      this.pageSize = val;
      this.loadData();
    },
    
    handleCurrentChange(val) {
      this.currentPage = val;
      this.loadData();
    },

    getUserName(row) {
      if (row.userName) return row.userName;
      if (row.user && row.user.name) return row.user.name;
      return this.$t('common.unknown');
    },

    getGroupName(row) {
      if (row.groupName) return row.groupName;
      if (row.user && row.user.userGroup) return row.user.userGroup;
      return this.$t('common.unknown');
    },

    getCourseName(row) {
      if (row.courseName) return row.courseName;
      if (row.course && row.course.name) return row.course.name;
      return this.$t('common.unknown');
    },

    getFilterGroupName() {
      const group = this.groups.find(g => g.id === this.filterForm.groupId);
      return group ? group.name : this.$t('common.unknown');
    },

    getFilterCourseName() {
      const course = this.courses.find(c => c.id === this.filterForm.courseId);
      return course ? course.name : this.$t('common.unknown');
    },

    getStateText() {
      const state = this.filterForm.state;
      if (state === null) return this.$t('common.all');
      const statusMap = {
        1: this.$t('attendance.checkAdmin.approved'),
        2: this.$t('attendance.checkAdmin.rejected')
      };
      return statusMap[state] || this.$t('common.all');
    },

    handleDateRangeChange(value) {
      if (value) {
        this.filterForm.startDate = value[0];
        this.filterForm.endDate = value[1];
      } else {
        this.filterForm.startDate = null;
        this.filterForm.endDate = null;
      }
      this.handleFilter();
    },

    removeFilter(filterType) {
      if (filterType === 'dateRange') {
        this.filterForm.dateRange = [];
        this.filterForm.startDate = null;
        this.filterForm.endDate = null;
      } else {
        this.filterForm[filterType] = '';
      }
      this.handleFilter();
    },

    getRowClassName({ row }) {
      if (row.state === 0) {
        return 'pending-row';
      }
      return '';
    },

    // 获取请假类型名称
    getLeaveTypeName(typeId) {
      if (!typeId) return this.$t('common.unknown');
      const type = this.leaveTypes.find(t => t.id === parseInt(typeId));
      if (!type) return this.$t('common.unknown');
      
      // 对常见的请假类型进行国际化转换
      const typeTranslateMap = {
        '病假': 'attendance.checkAdmin.sickLeave',
        '事假': 'attendance.checkAdmin.personalLeave',
        '其他请假': 'attendance.checkAdmin.otherLeave'
      };
      
      // 如果是预设的请假类型，则使用国际化翻译
      if (typeTranslateMap[type.name]) {
        return this.$t(typeTranslateMap[type.name]);
      }
      
      // 对于其他未预设的请假类型，直接返回原始名称
      return type.name;
    },
    
    // 获取请假类型标签样式
    getLeaveTypeTagType(typeId) {
      if (!typeId) return '';
      const typeMap = {
        1: 'info',    // 事假
        2: 'danger',  // 病假
        3: 'warning', // 公假
        4: 'success'  // 其他
      };
      return typeMap[typeId] || '';
    }
  }
}
</script>

<style scoped>
.check-admin-history-container {
  padding: 20px;
}

.filter-card {
  margin-bottom: 20px;
}

.filter-form {
  display: flex;
  justify-content: flex-start;
  flex-wrap: wrap;
}

.filter-status {
  margin-bottom: 15px;
  display: flex;
  align-items: center;
  flex-wrap: wrap;
}

.filter-status span {
  margin-right: 10px;
  color: #606266;
  font-size: 14px;
}

.filter-status .el-tag {
  margin-right: 10px;
  margin-bottom: 5px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

/* 待审批行高亮样式 */
::v-deep .pending-row {
  background-color: rgba(255, 236, 184, 0.4);
}

/* 鼠标悬停时的样式 */
::v-deep .pending-row:hover > td {
  background-color: rgba(255, 236, 184, 0.7) !important;
}

@media screen and (max-width: 768px) {
  .check-admin-history-container {
    padding: 10px;
  }
  
  .filter-form {
    flex-direction: column;
  }
  
  .filter-form .el-form-item {
    margin-right: 0;
    margin-bottom: 10px;
  }
  
  .filter-form .el-select,
  .filter-form .el-date-picker {
    width: 100%;
  }
  
  .pagination-container {
    text-align: center;
  }
  
  .el-table {
    font-size: 12px;
  }
  
  .el-table th {
    padding: 8px 0;
  }
  
  .el-table td {
    padding: 5px 0;
  }
}
</style>